package com.jdd.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageExtendUtils {
	private static final Logger logger = LoggerFactory.getLogger(ImageExtendUtils.class);

	public static final String TYPE_JPG = ".jpg";
    public static final String TYPE_GIF = ".gif";
    public static final String TYPE_PNG = ".png";
    public static final String TYPE_BMP = ".bmp";
    public static final String TYPE_UNKNOWN = ".unknown";
	/**
	 * byte数组转换成16进制字符串
	 *
	 * @param src
	 * @return
	 */
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	/**
	 * 根据文件流判断图片类型
	 *
	 * @param b
	 * @return jpg/png/gif/bmp
	 */
	public static String getPicType(byte[] b) {
		String str = bytesToHexString(b);
		System.out.println(str);
		if (str == null) {
			return TYPE_UNKNOWN;
		}
		String type = str.toUpperCase();
		if (type.contains("FFD8FF")) {
			return TYPE_JPG;
		} else if (type.contains("89504E47")) {
			return TYPE_PNG;
		} else if (type.contains("47494638")) {
			return TYPE_GIF;
		} else if (type.contains("424D")) {
			return TYPE_BMP;
		} else {
			return TYPE_UNKNOWN;
		}
	}

	/**
	 * 得到文件后缀，不带点
	 * @param b
	 * @return
	 */
	public static String getPicTypeNoDot(byte[] b) {
		String str = bytesToHexString(b);
		if (str == null) {
			return "unknown";
		}
		String type = str.toUpperCase();
		if (type.contains("FFD8FF")) {
			return "jpg";
		} else if (type.contains("89504E47")) {
			return "png";
		} else if (type.contains("47494638")) {
			return "gif";
		} else if (type.contains("424D")) {
			return "bmp";
		} else {
			return "unknown";
		}
	}

	/**
	 * @Author liujunwei
	 * @Description 计算图片大小
	 * @Date 9:41 2019/8/13
	 * @Param [image]
	 * @return java.lang.Integer
	 **/
	public static Integer imageSize(String image){
		// 1.需要计算文件流大小，首先把头部的data:image/png;base64,（注意有逗号）去掉。
		String str= null;
		if (image.length()>22){
			str=image.substring(22);
		}
		str =image;
		//2.找到等号，把等号也去掉
		Integer equalIndex= str.indexOf("=");
		if(str.indexOf("=")>0) {
			str=str.substring(0, equalIndex);
		}
		//3.原来的字符流大小，单位为字节
		Integer strLength=str.length();
		//4.计算后得到的文件流大小，单位为字节
		Integer size= strLength - (strLength/8)*2;
		logger.info("图片大小：{}k",size/1024);
		return size;
	}
}
